package cn.itcast.md.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.itcast.controller.IpBean;
import cn.itcast.md.dto.AiMdGoodsList;
import cn.itcast.md.dto.AiMdOrder;
import cn.itcast.utils.DingDingUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;

/***
 * 谜底世界
 */
@RestController
@Slf4j
public class MdController {
    private static List<IpBean> list=new ArrayList<>();
    private static List<String> tokenList=new ArrayList<>();
    @RequestMapping("/createMdMarket")
    public String createMdMarket(@RequestParam(value = "num",defaultValue = "10000") Integer num,
                               @RequestParam(value = "salePrice",defaultValue = "29") String salePrice,
                               @RequestParam(value = "goodsId",defaultValue = "24") String goodsId) {
        if(CollectionUtils.isEmpty(list)){
            try{
                IpBean ipBean1 = new IpBean();
                ipBean1.setIpAddress("117.160.250.132");
                ipBean1.setPort(8080);
                list.add(ipBean1);
            }catch (Exception e){
                IpBean ipBean=new IpBean();
                list.add(ipBean);
            }
        }
        if(CollectionUtils.isEmpty(tokenList)){
            addToken();
        }
        for(int i=0;i<num;i++){
            try {
                for(int j=0;j<list.size();j++){
                    for(int z=0;z<tokenList.size();z++){
                        IpBean ipBean=list.get(j);
                        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ipBean.getIpAddress(), ipBean.getPort()));
                        confireMarketOrder(proxy,tokenList.get(z),goodsId,salePrice);
                        Thread.sleep(1000);
                    }

                }
            } catch (Exception e) {
                log.error("#####异常####" + e.getMessage());
            }
        }
        log.info("####热浪执行完成#####");
        return null;
    }
    public void confireMarketOrder(Proxy proxy,String token,String goodsId,String salePrice){
        try{
            createMarketOrder(proxy,token,goodsId,salePrice);
        }catch (Exception e){
            log.error("#####创建订单失败####"+e.getMessage()+"###"+token);
        }
    }
    public void createMarketOrder(Proxy proxy,String token,String goodsId,String salePrice) throws InterruptedException {
        JSONObject requestJson = new JSONObject();
        requestJson.putOnce("goods_id", goodsId);
        requestJson.putOnce("goods_type", 2);
        requestJson.putOnce("keywords", "");
        requestJson.putOnce("list_rows", "100");
        requestJson.putOnce("new", "");
        requestJson.putOnce("page", 1);
        requestJson.putOnce("price", 2);
        requestJson.putOnce("series_id", "");
        requestJson.putOnce("status", "");
        requestJson.putOnce("type", 0);
        AiMdGoodsList aiMdGoodsList=null;
        String result=null;
        try{
            result = HttpRequest.post("https://api.riddlenft.cn/api/market/market/marketList")
                    .body(requestJson.toString())
                    .execute().body();
            aiMdGoodsList= JSONUtil.toBean(result, AiMdGoodsList.class);
        }catch (Exception e){
            log.info("####请求商品数据异常######"+e.getMessage()+"####"+result);
        }
        if(aiMdGoodsList!=null && aiMdGoodsList.getCode()==1){
            List<AiMdGoodsList.AiMdGoodsDetailList> goodsList= aiMdGoodsList.getData().getData();
            if(!CollectionUtils.isEmpty(goodsList)){
                for(AiMdGoodsList.AiMdGoodsDetailList goodsEntity:goodsList){
                    if(goodsEntity.getPayText()==0 && new BigDecimal(goodsEntity.getPrice()).compareTo(new BigDecimal(salePrice))<=0){
                        Proxy finalProxy = proxy;
                        saveOrder(finalProxy,token,goodsEntity.getId(),goodsId);
//                        ThreadUtil.execAsync(() -> {
//                            saveOrder(finalProxy,token,goodsEntity.getId(),goodsId);
//                        });
                        Thread.sleep(500);
                    }
                }
            }
        }
    }
    public void saveOrder(Proxy proxy,String token,String id,String goodsId){
        JSONObject createJson = new JSONObject();
        createJson.putOnce("market_goods_id", id);
        createJson.putOnce("pay_type", 21);
        String createResult = HttpRequest.post("https://api.riddlenft.cn//api/order/pay/CreateMarketOrder").
                body(createJson.toString())
                .header("token",token)
                .execute().body();
        log.info("####支付结果######"+createResult);
        AiMdOrder aiMdOrder= JSONUtil.toBean(createResult, AiMdOrder.class);
        if(aiMdOrder!=null && aiMdOrder.getCode() ==1){
            //请求数据生成url连接
            log.error("####生成订单数据######"+aiMdOrder.getData().getOrderSn());
            DingDingUtils.sendMsg("谜底您有一个新的订单，请赶紧支付");
        }
    }
    public void addToken(){
        tokenList.add("370519ec-c486-4d1b-b168-f66f34a4867c");
    }
}
